// 与数据库打交道
const { create, del, list, count, get } = require('../model/log')

const { Success, SysErr } = require('../response/code')

class LogService {
  async create(ctx) {
    try {
      const data = ctx.request.body
      data.project_id = ctx.state.project_id
      const result = await create(data)
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async get(ctx) {
    try {
      const query = ctx.request.query
      const project_id = ctx.state.project_id
      console.log(ctx.state, '<<< state')
      const result = await get(query.id, {
        project_id: project_id,
      })
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async del(ctx) {
    try {
      const body = ctx.request.body
      const project_id = ctx.state.project_id
      // 存在则删除
      const result = await del(body.id, {
        project_id: project_id,
        deleted_at: null,
      })
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async list(ctx) {
    try {
      const query = ctx.request.query
      const project_id = ctx.state.project_id
      const where = {
        deleted_at: {
          equals: null, // 为 null
        },
        project_id: project_id,
      }
      const data = await list(query.pageNo, query.pageSize, where) // 可以添加第三个参数条件过滤
      const total = await count(where)
      const result = {
        list: data,
        count: total,
      }
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }
}
module.exports = new LogService()
